import Backend, {org_id, lrs_id} from "../../../components/Backend/Backend";
import {call, put} from 'redux-saga/effects';
import {v4 as uuid4} from 'uuid';
import parse from "html-react-parser";
import {
  requestIndicatorsPreviewByUserName,
  requestCompositeVisualizationPreview
} from "../request/compositeEditor";

import {
  setGeneratedVisualizationCode
} from "../../reducers/editor";
import {
  setBasicIndicatorPreviewList
} from "../../reducers/compositeEditor";
export function* handleIndicatorsPreviewByUserName() {
  try {
    const parsedUser = JSON.parse(localStorage.getItem('openlapUser'));
    const userName = parsedUser.email;
    const response = yield call(requestIndicatorsPreviewByUserName, userName);
    const {data} = response;
    console.log('data',data)

    if (data !== undefined) {
      let _data={}
      for(let i in data){
        _data[data[i]['id']] = data[i]
      }
      // const sortedArray = (data.columns["statement.context.platform"].data).sort((a, b) => a.localeCompare(b));
      yield put(setBasicIndicatorPreviewList(_data));
    }
  } catch (error) {
    alert('error',error)
  }
}


export function* handleCompositeVisualizationPreview(action) {
  const query = action.payload.queryBuilder;
  try {
    const response = yield call(requestCompositeVisualizationPreview, query);
    const unescapedVizCode = decodeURIComponent(response.data.visualizationCode);
    let displayCode = parse(unescapedVizCode);
    let scriptData = displayCode[1].props.dangerouslySetInnerHTML.__html;
    yield put(setGeneratedVisualizationCode(displayCode, scriptData, ""));
  } catch (error) {
    let errorMessage = "Visualization not possible!"
    yield put(setGeneratedVisualizationCode("", "", errorMessage));
  }
}
